import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import 'package:ls_work/chart/char_widget.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/net/response/response_data.dart';
import 'package:ls_work/net/response/service_order_statistics_data.dart';
import 'package:ls_work/net/response/service_order_year_statistics_data.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/widgets/static_chat_bar_widget.dart';

class ServiceOrderStatisticsViewModel extends BaseViewModel {
  ServiceOrderStatisticsViewModel(BuildContext context) : super(context);
  static const List<String> _formats = [yyyy, '-', mm];
  static const List<String> _yearFormats = [yyyy];
  var month = DateTime.now().toDateStr(_formats);
  var year = DateTime.now().toDateStr(_yearFormats);

  var _total = "0";
  var _djd = "0";
  var _dfw = "0";
  var _fwz = "0";
  var _ywc = "0";

  ServiceOrderYearStatisticsData? yearData;

  void selectMonth(){
    DatePicker.showMonthPicker(context,maxTime: DateTime.now(),onConfirm: (date){
      month = date?.toDateStr(_formats)??"";
      notifyListeners();
      getStatisticsData();
    });
  }

  void selectYear(){
    var currentYear = DateTime.now().year;
    List<int> list = [];
    for(var i=0;i<=50;i++){
      list.add(currentYear-i);
    }
    var data = list.reversed.map((e) => YearData(e, '${e}年')).toList();

    DataPickerView(context, data,currentFirstData: data.last,onSubmitListener: (p1,p2,p3){
      var item = data[p1];
      year = item.year.toString();
      notifyListeners();
      getYearStatistics();
    }).show();
  }

  ///工单统计数
  Widget topStatisticsWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        _statisticsText(_total, '总数'),
        _statisticsText(_djd, '待接单'),
        _statisticsText(_dfw, '待服务'),
        _statisticsText(_fwz, '服务中'),
        _statisticsText(_ywc, '已完成'),
      ],
    ).addToContainer(
        margin: EdgeInsets.symmetric(vertical: 10),
        height: 160,
        alignment: Alignment.center,
        color: Colors.white);
  }

  Widget _statisticsText(String num, String title) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        CommonText(num,
            textSize: 24,
            textColor: Colours.app_main,
            fontWeight: FontWeight.w600),
        Container(
          height: 16,
        ),
        CommonText(title, textSize: 14, textColor: Colours.text_gray_9)
      ],
    );
  }

  ///工单统计
  Widget orderStatusWidget() {
    var items = [
      PieData(_djd.toDouble()??0, Colours.un_receive_order, (_djd??"0").toDouble()!/_total.toDouble()!*100, title: "待接单"),
      PieData(_dfw.toDouble()??0, Colours.un_service_order, (_dfw??"0").toDouble()!/_total.toDouble()!*100, title: "待服务"),
      PieData(_fwz.toDouble()??0, Colours.un_rate_order, (_fwz??"0").toDouble()!/_total.toDouble()!*100, title: "服务中"),
      PieData(_ywc.toDouble()??0, Colours.has_rate_order, (_ywc??"0").toDouble()!/_total.toDouble()!*100, title: "已完成"),
    ];

    return Column(
      children: [
        Row(
          children: [
            CommonText('工单状态', textSize: 20, fontWeight: FontWeight.w600)
                .setWeight(1),
            Row(
              children: [
                CommonText(month),
                Container(
                  width: 5,
                ),
                Icon(
                  Ionicons.calendar_outline,
                  color: Colours.app_main,
                ),
              ],
            ).onTap(() {
              selectMonth();
            })
          ],
        ),
         AspectRatio(
          aspectRatio: 1.8,
          child: _total=="0"?Center(
            child: CommonText('暂无数据',),
          ):Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              PieChartWidget(
                items,
                centerRadius: 60,
                pieWidth: 20,
                showTitle: false,
                isEmptyData: _total.toDouble()==0,
              ).setWeight(1),
              Column(
                mainAxisSize: MainAxisSize.min,
                mainAxisAlignment: MainAxisAlignment.center,
                children: items
                    .map((e) => Row(
                          children: [
                            Container(
                              width: 8,
                              height: 8,
                              margin: EdgeInsets.only(right: 10, left: 16),
                              decoration: BoxDecoration(
                                  color: e.color, shape: BoxShape.circle),
                            ),
                            CommonText(
                              '${e.title}   ${(e.percent??0).toStringAsFixed(2)}%',
                              textColor: Color(0xff62656A),
                              textSize: 15,
                            )
                          ],
                        ).addToContainer(height: 32))
                    .toList(),
              ).setWeight(1)
            ],
          ),
        )
      ],
    ).addToContainer(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 13, vertical: 16));
  }

  Widget monthOrderNum() {
    var items = [
      ChartData("待接单"),
      ChartData("待服务"),
      ChartData("待评价"),
      ChartData("已评价"),
    ];

    if(yearData==null){
      items.forEach((element) {
        element.datas = [
          SalesData("1月", 0),
          SalesData("2月", 0),
          SalesData("3月", 0),
          SalesData("4月", 0),
          SalesData("5月", 0),
          SalesData("6月", 0),
          SalesData("7月", 0),
          SalesData("8月", 0),
          SalesData("9月", 0),
          SalesData("10月", 0),
          SalesData("11月", 0),
          SalesData("12月", 0),
        ];
      });
    }else{
      (items??[]).forEach((element) {
        if(element.groupName=='待接单'){
          element.datas = [
            SalesData("1月", yearData?.januaryDjd?.toDouble()??0),
            SalesData("2月", yearData?.februaryDjd?.toDouble()??0),
            SalesData("3月", yearData?.marchDjd?.toDouble()??0),
            SalesData("4月", yearData?.aprilDjd?.toDouble()??0),
            SalesData("5月", yearData?.mayDjd?.toDouble()??0),
            SalesData("6月", yearData?.julyDjd?.toDouble()??0),
            SalesData("7月", yearData?.juneDjd?.toDouble()??0),
            SalesData("8月", yearData?.augustDjd?.toDouble()??0),
            SalesData("9月", yearData?.septemberDjd?.toDouble()??0),
            SalesData("10月", yearData?.octoberDjd?.toDouble()??0),
            SalesData("11月", yearData?.novemberDjd?.toDouble()??0),
            SalesData("12月", yearData?.decemberDjd?.toDouble()??0),
          ];
        }
        if(element.groupName=='待服务'){
          element.datas = [
            SalesData("1月", yearData?.januaryDfw?.toDouble()??0),
            SalesData("2月", yearData?.februaryDfw?.toDouble()??0),
            SalesData("3月", yearData?.marchDfw?.toDouble()??0),
            SalesData("4月", yearData?.aprilDfw?.toDouble()??0),
            SalesData("5月", yearData?.mayDfw?.toDouble()??0),
            SalesData("6月", yearData?.julyDfw?.toDouble()??0),
            SalesData("7月", yearData?.juneDfw?.toDouble()??0),
            SalesData("8月", yearData?.augustDfw?.toDouble()??0),
            SalesData("9月", yearData?.septemberDfw?.toDouble()??0),
            SalesData("10月", yearData?.octoberDfw?.toDouble()??0),
            SalesData("11月", yearData?.novemberDfw?.toDouble()??0),
            SalesData("12月", yearData?.decemberDfw?.toDouble()??0),
          ];
        }

        if(element.groupName=='待评价'){
          element.datas = [
            SalesData("1月", yearData?.januaryDpj?.toDouble()??0),
            SalesData("2月", yearData?.februaryDpj?.toDouble()??0),
            SalesData("3月", yearData?.marchDpj?.toDouble()??0),
            SalesData("4月", yearData?.aprilDpj?.toDouble()??0),
            SalesData("5月", yearData?.mayDpj?.toDouble()??0),
            SalesData("6月", yearData?.julyDpj?.toDouble()??0),
            SalesData("7月", yearData?.juneDpj?.toDouble()??0),
            SalesData("8月", yearData?.augustDpj?.toDouble()??0),
            SalesData("9月", yearData?.septemberDpj?.toDouble()??0),
            SalesData("10月", yearData?.octoberDpj?.toDouble()??0),
            SalesData("11月", yearData?.novemberDpj?.toDouble()??0),
            SalesData("12月", yearData?.decemberDpj?.toDouble()??0),
          ];
        }

        if(element.groupName=='已评价'){
          element.datas = [
            SalesData("1月", yearData?.januaryYpj?.toDouble()??0),
            SalesData("2月", yearData?.februaryYpj?.toDouble()??0),
            SalesData("3月", yearData?.marchYpj?.toDouble()??0),
            SalesData("4月", yearData?.aprilYpj?.toDouble()??0),
            SalesData("5月", yearData?.mayYpj?.toDouble()??0),
            SalesData("6月", yearData?.julyYpj?.toDouble()??0),
            SalesData("7月", yearData?.juneYpj?.toDouble()??0),
            SalesData("8月", yearData?.augustYpj?.toDouble()??0),
            SalesData("9月", yearData?.septemberYpj?.toDouble()??0),
            SalesData("10月", yearData?.octoberYpj?.toDouble()??0),
            SalesData("11月", yearData?.novemberYpj?.toDouble()??0),
            SalesData("12月", yearData?.decemberYpj?.toDouble()??0),
          ];
        }


      });
    }
    return Column(
      children: [
        Row(
          children: [
            CommonText('工单数量（每月）', textSize: 20, fontWeight: FontWeight.w600)
                .setWeight(1),
            Row(
              children: [
                CommonText(year),
                Container(
                  width: 5,
                ),
                Icon(
                  Ionicons.calendar_outline,
                  color: Colours.app_main,
                ),
              ],
            ).onTap(() {
              selectYear();
            })
          ],
        ),
        AspectRatio(
          aspectRatio: 1,
          child: StackBarWidget(list: items,)
        )

      ],
    ).addToContainer(
        color: Colors.white,
        padding: EdgeInsets.symmetric(horizontal: 13, vertical: 16));
  }

  Future<void> getStatisticsData() async {
    showLoadingDialog();
    try {
      var data = await PostRequest.serviceOrderStatistics(month);
      hideDialog();
      var bean = ResponseBean.fromJson(data);
      if ("0" == bean.code) {
        var item = ServiceOrderStatisticsData.fromJson(bean.data[0]);

        _djd = item.djd??"0";
        _dfw = item.dfw??"0";
        _fwz = item.fwz??"0";
        _ywc = item.dpj??"0";
        _total = (_djd.toInteger() +
                _dfw.toInteger() +
                _fwz.toInteger() +
                _ywc.toInteger())
            .toString();
        notifyListeners();
      } else {
        showToast(bean.msg??"");
      }
    } catch (e) {
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }

  Future<void> getYearStatistics() async {
    showLoadingDialog();
    try{
      var data = await PostRequest.serviceYearStatistics(year);
      hideDialog();
      var res = ResponseBean.fromJson(data);
      if("0"==res.code){
        yearData = ServiceOrderYearStatisticsData.fromJson(res.data);
        notifyListeners();
      }else{
        showToast(res.msg??"");
      }
    }catch(e){
      hideDialog();
      showToast(NetErrorUtils.getNetError(e));
    }
  }



  @override
  void onCreated() {
    super.onCreated();
    getStatisticsData();
    getYearStatistics();
  }

}

class YearData implements IPickerData{
  int year;
  String yearName;


  YearData(this.year, this.yearName);

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
          other is YearData && runtimeType == other.runtimeType &&
              year == other.year && yearName == other.yearName;

  @override
  int get hashCode => year.hashCode ^ yearName.hashCode;

  @override
  String get name => yearName;

  @override
  set name(String _name) {
  }


}

class StackBarWidget extends StatelessWidget{
  List<ChartData> list;


  StackBarWidget({required this.list});

  @override
  Widget build(BuildContext context) {
    var map = {
      "tooltip": {
        "trigger": 'axis',
        "axisPointer": {
          // Use axis to trigger tooltip
          "type": 'shadow' // 'shadow' as default; can also be 'line' or 'shadow'
        }
      },
      "legend": {},
      "grid": {
        "left": '3%',
        "right": '4%',
        "bottom": '3%',
        "top":"8%",
        "containLabel": true
      },
      "xAxis": {
        "type": 'value'
      },
      "yAxis": {
        "type": 'category',
        "data": (list.first.datas??[]).map((e)=>e.name).toList()
      },
      "series": list.map((e)=>{
        "name": '${e.groupName}',
        "type": 'bar',
        "stack": 'total',
        "label": {
          "show": false
        },
        "emphasis": {
          "focus": 'series'
        },
        "data": e.datas?.map((item)=>item.value).toList()
      }).toList()
    };
    return list.isEmpty?Container(
      child: CommonText('暂无数据'),
      alignment: Alignment.center,
    ): Echarts(option: jsonEncode(map))
        ;
  }

}

